package com.sbio.udiapp.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbio.udiapp.R;
import com.sbio.udiapp.adapter.PackingListViewAdapter;
import com.sbio.udiapp.common.bean.PackVo;
import com.sbio.udiapp.common.bean.PrintVo;
import com.sbio.udiapp.cpcl.PrintUtil;
import com.sbio.udiapp.databinding.ActivityUnpackingBinding;
import com.sbio.udiapp.net.api.ApiService;
import com.sbio.udiapp.net.exception.ApiException;
import com.sbio.udiapp.net.exception.ErrorConsumerAdapter;
import com.sbio.udiapp.net.response.ResponseTransformer;
import com.sbio.udiapp.util.CollectionUtils;
import com.sbio.udiapp.util.CommonUtil;
import com.sbio.udiapp.util.DefaultSharedPreferencesUtil;
import com.sbio.udiapp.util.DialogUtil;
import com.sbio.udiapp.util.IntentUtil;
import com.sbio.udiapp.util.JsonUtil;
import com.sbio.udiapp.util.LogUtil;
import com.sbio.udiapp.util.SharedPreferencesUtil;
import com.sbio.udiapp.util.ToastUtil;
import com.sbio.udiapp.util.VibratorUtil;
import com.sbio.udiapp.util.ViewUtil;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class UnpackingActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityUnpackingBinding binding;

    private final ObservableList<String> datas = new ObservableArrayList<>();

    private PackingListViewAdapter packingListViewAdapter;

    @Inject
    ApiService apiService;

    AtomicInteger progressCount = new AtomicInteger();

    private BroadcastReceiver broadcastReceiver;

    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUnpackingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initSystemScanData();
        binding.etMaxCount.requestFocus();
        /*//箱码扫描框绑定事件-回车自动拆箱，并将拆箱数据填写到datas中
        binding.packCodeScan.setOnEditorActionListener((v, actionId, event) -> {
            unpacking();
            return true;
        });*/

        //盒码扫描框绑定事件-回车添加数据
        /*binding.boxCodeScan.setOnEditorActionListener((v, actionId, event) -> {
            if (addBoxCode()) return true;

            return false;
        });*/

        binding.removeXm.setOnClickListener(v -> {
            binding.packCodeScan.setText("");
            datas.clear();
            packingListViewAdapter.notifyDataSetChanged();
        });

        //设置listViewAdapter
        packingListViewAdapter = new PackingListViewAdapter(this, binding.boxCodeScan, datas);
        binding.lvBoxCode.setAdapter(packingListViewAdapter);

        //装箱按钮绑定事件
        binding.btnPacking.setOnClickListener(this);
        packingListViewAdapter.notifyDataSetChanged();


        datas.addOnListChangedCallback(new ObservableList.OnListChangedCallback<ObservableList<String>>() {
            @Override
            public void onChanged(ObservableList<String> sender) {
                setTitle(getString(R.string.unpacking) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeChanged(ObservableList<String> sender, int positionStart, int itemCount) {
                setTitle(getString(R.string.unpacking) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeInserted(ObservableList<String> sender, int positionStart, int itemCount) {
                setTitle(getString(R.string.unpacking) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeMoved(ObservableList<String> sender, int fromPosition, int toPosition, int itemCount) {
                setTitle(getString(R.string.unpacking) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeRemoved(ObservableList<String> sender, int positionStart, int itemCount) {
                setTitle(getString(R.string.unpacking) + "(" + datas.size() + "个)");
            }
        });
    }

    private boolean addBoxCode(String boxCode) {
        String maxCountStr = binding.etMaxCount.getText().toString();
        Integer maxCount = null;
        if (!TextUtils.isEmpty(maxCountStr)) {
            maxCount = Integer.valueOf(maxCountStr);
            if (datas.size() >= maxCount) {
                DialogUtil.showCommonAlertDialog("已经达到最大数量");
                return true;
            }
        }
        if (datas.contains(boxCode)) {
            DialogUtil.showCommonAlertDialog("数据重复");
            return true;
        }
        String data0 = "";
        if (DefaultSharedPreferencesUtil.useDeptIsProduct(this) && CollectionUtils.isNotEmpty(datas)) {
            data0 = datas.get(0);
        }

        String useDept = DefaultSharedPreferencesUtil.getUseDept(this);
        Integer finalMaxCount = maxCount;
        apiService.checkPackScanBoxCode(boxCode, data0, useDept)
                .compose(ResponseTransformer.obtain())
                .subscribe(ajaxResult -> {
                    if (ajaxResult.getData(Boolean.class) && !datas.contains(boxCode)) {
                        ToastUtil.show(R.string.toast_add_success);
                        datas.add(boxCode);
                        packingListViewAdapter.notifyDataSetChanged();
                        if (finalMaxCount != null && datas.size() == finalMaxCount) {
                            //达到最大震动一下
                            VibratorUtil.vibrator();
                        }
                        return;
                    }
                    //弹出提示框
                    DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                }, new ErrorConsumerAdapter());
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public boolean unpacking() {
        String packNo = binding.packCodeScan.getText().toString();
        if (TextUtils.isEmpty(packNo)) {
            return true;
        }
        apiService.getBoxNoList(packNo)
                .compose(ResponseTransformer.obtain())
                .subscribe(ajaxResult -> {
                    //显示拆箱结果
                    List<String> udiBoxNos = ajaxResult.getDataList(String.class);
                    ToastUtil.show(ajaxResult.getMsg());
                    if (udiBoxNos == null || udiBoxNos.size() == 0) {
                        binding.packCodeScan.setText("");
                        packingListViewAdapter.notifyDataSetChanged();
                        //获取焦点
                        binding.packCodeScan.postDelayed(() -> {
                            binding.packCodeScan.requestFocus();
                        }, 100);
//                        binding.packCodeScan.requestFocus();
                        return;
                    }
                    //成功提示
                    ToastUtils.showLong("拆箱成功");
                    //添加不存在的盒码

                    udiBoxNos.stream().filter(no -> !datas.contains(no)).forEach(datas::add);
                    //删除所有盒码
//                    apiService.unpacking(packNo);
                    //刷新adapter
                    packingListViewAdapter.notifyDataSetChanged();
                }, new ErrorConsumerAdapter() {
                    @Override
                    public void error(ApiException ex) {
                        super.error(ex);
                        //处理异常
                        ToastUtil.show(ex.getErrMsg());
                    }
                });
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 装箱按钮绑定事件
            case R.id.btn_packing: {
                PackVo pack = new PackVo();
                String packNo = binding.packCodeScan.getText().toString();
                pack.setPackNo(packNo);
                pack.setBoxCode(datas);
                pack.setPackStatus(PackVo.packed);
                apiService.packing(pack)
                        .compose(ResponseTransformer.obtain())
                        .subscribe(ajaxResult -> {
                            ToastUtil.show(R.string.submit_success);
                            binding.packCodeScan.setText("");
                            ViewUtil.requestFocus(binding.packCodeScan);

                            Object data = ajaxResult.getData();
                            ObjectMapper objectMapper = new ObjectMapper();
                            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                            PrintVo printVo = objectMapper.convertValue(data, PrintVo.class);
                            SharedPreferencesUtil.saveString("printVo", JsonUtil.toJsonString(printVo));
                            PrintUtil.printQR(printVo);

                            //清空数据并刷新页面
                            datas.clear();
                            packingListViewAdapter.notifyDataSetChanged();
                            //返回主页
//                            Intent intent = new Intent(this, MainActivity.class);
//                            startActivity(intent);
                        }, new ErrorConsumerAdapter());

                break;
            }
            default:
                break;
        }
    }


    public void initSystemScanData() {

        // 新建一个广播接收对象，实现数据接收和处理
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    if (action == null) {
                        return;
                    }
                    String data = IntentUtil.getStringExtra(intent);

                    switch (action) {
                        case IntentUtil.INTENT_ACTIONS_DEFAULT_1:
                        case IntentUtil.INTENT_ACTIONS_DEFAULT_2:
                            onBroadcastReceiver(data);
                        default:
                            break;
                    }
                } catch (Exception e) {
                    DialogUtil.showCommonAlertDialog(e.getMessage());
                }
            }

            private void onBroadcastReceiver(String barcodeData) {

                LogUtil.file("接收到广播数据", barcodeData);
                if (progressCount.get() > 0) {
                    ToastUtil.showWait("请等待上一个结果返回");
                    return;
                }
                if (datas.contains(barcodeData)) {
                    ToastUtil.showError("数据重复");
                    return;
                }
                //如果是出库申请开头的数据那么就是outStockApplyNos
                if (CommonUtil.isPbNo(barcodeData)) {


                    if (StringUtils.isEmpty(binding.packCodeScan.getText().toString())) {
                        if (!CommonUtil.isPack(barcodeData)) {
                            ToastUtil.showError("请先输入拆箱的箱码");
                        }
                        //如果为空，则是拆箱
                        binding.packCodeScan.setText(barcodeData);
                        unpacking();
                    } else {
                        addBoxCode(barcodeData);
                    }
                } else {
                    //非法数据
                    ToastUtil.showError("非法数据，请检查");
                }
            }
        };
        intentFilter = new IntentFilter();
        intentFilter.addAction(IntentUtil.INTENT_ACTIONS_DEFAULT_1);
        intentFilter.addAction(IntentUtil.INTENT_ACTIONS_DEFAULT_2);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册广播接收器
        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver); // 取消广播注册
        }
        super.onPause();
    }
}